package com.labor_management_system.Controller;

import com.alibaba.fastjson2.JSONArray;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.labor_management_system.Entity.*;
import com.labor_management_system.Service.AttendanceService;
import com.labor_management_system.Service.EmployeeService;
import com.labor_management_system.Service.EnterprisesService;
import com.labor_management_system.Service.TeamService;
import com.labor_management_system.Utils.Pair;
import com.labor_management_system.Utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

//考勤信息和考勤明细的查（信息展示一个班组的，明细展示对应班组的个人考勤信息）：
//        考勤信息：
//        通过班组名称查
//        通过考勤月份筛
//        考勤明细：
//        通过工人姓名查
//        考勤月份查
//        分页查询
@RestController
@CrossOrigin
public class AttendanceStatisticsController {
    //考勤统计管理ME
    @Autowired
    AttendanceService attendanceService;
    @Autowired
    TeamService teamService;
    @Autowired
    EmployeeService employeeService;
@Autowired
    EnterprisesService enterprisesService;
    List<TeamAttendance> teamAttendanceList;
    Map<String,List<String>> TeamVEmployee;
    List<TeamAttendanceDetails> teamAttendanceDetailsList;

    //创建考勤信息
    @PostMapping("/GET/SimulateWorking")
    public R simulateWorking(@RequestParam(value="employeeNumber")int number){
        Set<String> processedEmployeeIds = new HashSet<>();

        employeeService.getBaseMapper().selectObjs(new QueryWrapper<Employee>()
                        .select("employee_id")
                        .orderByAsc("RAND()")
                        .last("LIMIT " + number))
                .stream()
                .map(obj -> obj.toString())
                .collect(Collectors.toList()).forEach(id -> {
                    if (!processedEmployeeIds.contains(id)) { // 检查是否已经处理过该员工
                        long currentTime = System.currentTimeMillis();
                        long startOf2023 = getMidnightTimestampOfYear(2023);
                        long endOf2023 = getMidnightTimestampOfYear(2024) - 1; // 结束时间设置为2023年的最后一刻

                        // 查询2023年是否已经有该员工的考勤信息
                        Long count = attendanceService.getBaseMapper().selectCount(new QueryWrapper<Attendance>()
                                .eq("employee_id", id)
                                .between("start_work", startOf2023, endOf2023));

                        if (count == 0) { // 如果2023年还没有该员工的考勤信息，则插入新的考勤信息
                            long randomOffset = new Random().nextLong() % (365 * 24 * 60 * 60 * 1000); // 一年的毫秒数
                            long startTime = startOf2023 + randomOffset;
                            long endTime = startTime + (new Random().nextInt(8) + 1) * 60 * 60 * 1000; // 随机生成1到8小时的工作时长
                            attendanceService.getBaseMapper().insert(new Attendance(id, startTime, endTime));
                        }

                        processedEmployeeIds.add(id); // 将已处理的员工ID加入Set
                    }
                });

        return R.ok();
    }
    @PostMapping("/GET/SimulateWorking1")
    public R simulateWorking1(@RequestParam(value="employeeNumber")int number){
        Set<String> processedEmployeeIds = new HashSet<>();

        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(2024, 1, 1); // 设置为2024年2月1日
        long startOfToday = calendar.getTimeInMillis();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.MILLISECOND, -1);
        long endOfToday = calendar.getTimeInMillis();

        employeeService.getBaseMapper().selectObjs(new QueryWrapper<Employee>()
                        .select("employee_id")
                        .orderByAsc("RAND()")
                        .last("LIMIT " + number))
                .stream()
                .map(obj -> obj.toString())
                .collect(Collectors.toList()).forEach(id -> {
                    if (!processedEmployeeIds.contains(id)) { // 检查是否已经处理过该员工
                        long currentTime = System.currentTimeMillis();

                        // 查询当天是否已经有该员工的考勤信息
                        Long count = attendanceService.getBaseMapper().selectCount(new QueryWrapper<Attendance>()
                                .eq("employee_id", id)
                                .between("start_work", startOfToday, endOfToday));

                        if (count == 0) { // 如果当天还没有该员工的考勤信息，则插入新的考勤信息
                            long randomOffset = new Random().nextLong() % (24 * 60 * 60 * 1000); // 一天的毫秒数
                            calendar.setTimeInMillis(startOfToday + randomOffset);
                            long startTime = calendar.getTimeInMillis();
                            long endTime = startTime + (new Random().nextInt(8) + 1) * 60 * 60 * 1000; // 随机生成1到8小时的工作时长
                            attendanceService.getBaseMapper().insert(new Attendance(id, startTime, endTime));
                        }

                        processedEmployeeIds.add(id); // 将已处理的员工ID加入Set
                    }
                });

        return R.ok();
    }
    private long getMidnightTimestampOfYear(int year) {
        LocalDateTime startOfYear = LocalDateTime.of(year, 1, 1, 0, 0);
        return startOfYear.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    // 获取当天零点的时间戳
    private long getMidnightTimestampOfToday(long currentTime) {
        LocalDate today = Instant.ofEpochMilli(currentTime).atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDateTime startOfToday = LocalDateTime.of(today, LocalTime.MIDNIGHT);
        return startOfToday.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }
    //班组考勤信息
    //要求分页查询，按班组名称查询，考勤月份查询（传入对应的月份第一天0时时间+1）
    @PostMapping("/GET/GetTeamAttendanceAll")
    public R getTeamAttendanceAll(@RequestParam(value = "currentTime")Long currentTime,
                                  @RequestParam("pageNum") int pageNum,
                                  @RequestParam("pageSize") int pageSize){
        //先拿取teamid
        List<Team> teams = teamService.getAllTeam();
        TeamVEmployee=new HashMap<>();
        for (Team team : teams) {
            TeamVEmployee.put(team.getTeamId(), employeeService.getEmployeeIDByTeamID(team.getTeamId()));
        }
        teamAttendanceList = new ArrayList<>();


        //teamid查询当天的上班人数
        for (Team team : teams) {
            TeamAttendance t = new TeamAttendance();
            t.setTeamID(team.getTeamId());
            t.setTeamName(team.getTeamName());
            t.setNowWorkNumber(attendanceService.getWorkingNumber(TeamVEmployee.get(team.getTeamId()), currentTime));
            teamAttendanceList.add(t);

        }


        //teamid查询昨天的总上班时长和上班人数
        for(int i=0;i<teams.size();i++){
            //Map<String,List<String>> TeamVEmployee;
            Pair<Long,Double> temp = attendanceService.getYWorkNumber(TeamVEmployee.get(teams.get(i).getTeamId()),currentTime);
            teamAttendanceList.get(i).setYWorkingTime(temp.getSecond());
            teamAttendanceList.get(i).setYWorkNumber(temp.getFirst());
            //System.out.println();
            Pair<Long,Double> temp1 = attendanceService.getMWorkNumber(TeamVEmployee.get(teams.get(i).getTeamId()),currentTime);
            teamAttendanceList.get(i).setTTotalWorkingTimeM(temp1.getSecond());
            teamAttendanceList.get(i).setTTotalWorkNumberM(temp1.getFirst());
        }

        //teamid查询当前月份下与team联系的employee的总上班时长和当月累计上班人数
        //分页 pageNum pageSize [(pageNum-1)*20,(pageNum-1)*20+20]
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, teamAttendanceList.size());
        if (startIndex >= teamAttendanceList.size()){
            return R.error();
        }
        // 使用subList获取指定范围的子列表，并创建一个新的ArrayList
        List<TeamAttendance> pageData = new ArrayList<>(teamAttendanceList.subList(startIndex, endIndex));


        return R.ok().data("TeamAttendances",new JSONArray(pageData))
                     .data("TeamAttendancesSize",pageData.size());
    }
    @PostMapping("/GET/GetTeamAttendanceByTeamName")
    public R getTeamAttendanceByTeamName(@RequestParam(value = "currentTime")Long currentTime,
                                         @RequestParam(value = "teamName")String teamName,
                                         @RequestParam("pageNum") int pageNum,
                                         @RequestParam("pageSize") int pageSize){
        //在teamAttendances上做文章或者重新搜一遍
        //先拿取teamid
        List<Team> teams = teamService.getTeamByName(teamName);
        TeamVEmployee=new HashMap<>();
        for (Team team : teams) {
            TeamVEmployee.put(team.getTeamId(), employeeService.getEmployeeIDByTeamID(team.getTeamId()));
        }
        teamAttendanceList = new ArrayList<>();

        for (Team team : teams) {
            TeamAttendance t = new TeamAttendance();
            t.setTeamID(team.getTeamId());
            t.setTeamName(team.getTeamName());
            t.setNowWorkNumber(attendanceService.getWorkingNumber(TeamVEmployee.get(team.getTeamId()), currentTime));
            teamAttendanceList.add(t);
        }


        //teamid查询昨天的总上班时长和上班人数
        for(int i=0;i<teams.size();i++){
            Pair<Long,Double> temp = attendanceService.getYWorkNumber(TeamVEmployee.get(teams.get(i).getTeamId()),currentTime);
            teamAttendanceList.get(i).setYWorkingTime(temp.getSecond());
            teamAttendanceList.get(i).setYWorkNumber(temp.getFirst());
            temp = attendanceService.getMWorkNumber(TeamVEmployee.get(teams.get(i).getTeamId()),currentTime);
            teamAttendanceList.get(i).setTTotalWorkingTimeM(temp.getSecond());
            teamAttendanceList.get(i).setTTotalWorkNumberM(temp.getFirst());
        }

        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, teamAttendanceList.size());
        if (startIndex >= teamAttendanceList.size()){
            return R.error();
        }
        // 使用subList获取指定范围的子列表，并创建一个新的ArrayList
        List<TeamAttendance> pageData = new ArrayList<>(teamAttendanceList.subList(startIndex, endIndex));


        return R.ok().data("TeamAttendances",new JSONArray(pageData))
                     .data("TeamAttendancesSize",pageData.size());
    }

    //班组中个人的考勤明细 按姓名和月份查
    @PostMapping("/GET/GetTeamAttendanceDetails")
    public R getTeamAttendanceDetails(@RequestParam(value = "currentTime")Long currentTime,
                                      @RequestParam(value = "teamID")String teamID,
                                      @RequestParam("pageNum") int pageNum,
                                      @RequestParam("pageSize") int pageSize){

        teamAttendanceDetailsList = new ArrayList<>();
        List<String>employeeIDs = TeamVEmployee.get(teamID);
        for(String ID: employeeIDs){
            TeamAttendanceDetails t = new TeamAttendanceDetails();
            t.setEmployeeID(ID);
            t.setEmployeeName(employeeService.getEmployeeNameByID(ID));
            t.setWorkingTimes(attendanceService.getEmployeeAttendance(ID,currentTime));
            teamAttendanceDetailsList.add(t);
        }

        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, teamAttendanceDetailsList.size());
        if (startIndex >= teamAttendanceDetailsList.size()){
            return R.error();
        }
        // 使用subList获取指定范围的子列表，并创建一个新的ArrayList
        List<TeamAttendanceDetails> pageData = new ArrayList<>(teamAttendanceDetailsList.subList(startIndex, endIndex));

        return R.ok().data("TeamAttendances",new JSONArray(pageData))
                .data("TeamAttendancesSize",pageData.size());
    }
    @PostMapping("/GET/GetTeamAttendanceDetailsByName")
    public R getTeamAttendanceDetailsByName(@RequestParam(value = "currentTime")Long currentTime,
                                            @RequestParam(value = "teamID")String teamID,
                                            @RequestParam(value = "employeeName")String employeeName,
                                            @RequestParam("pageNum") int pageNum,
                                            @RequestParam("pageSize") int pageSize){

        teamAttendanceDetailsList = new ArrayList<>();
        List<String>employeeIDs = TeamVEmployee.get(teamID);
        List<String>employeeLikes = employeeIDs.stream()
                                    .filter(employeeService.getEmployeeIdByName(employeeName)::contains) // 过滤出同时存在于employeeLikes中的元素
                                    .collect(Collectors.toList()); // 收集结果到一个新的列表

        for(String ID: employeeLikes) {
            TeamAttendanceDetails t = new TeamAttendanceDetails();
            t.setEmployeeName(employeeService.getEmployeeNameByID(ID));
            t.setEmployeeID(ID);
            t.setWorkingTimes(attendanceService.getEmployeeAttendance(ID, currentTime));
            teamAttendanceDetailsList.add(t);
        }

        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, teamAttendanceDetailsList.size());
        if (startIndex >= teamAttendanceDetailsList.size()){
            return R.error();
        }
        // 使用subList获取指定范围的子列表，并创建一个新的ArrayList
        List<TeamAttendanceDetails> pageData = new ArrayList<>(teamAttendanceDetailsList.subList(startIndex, endIndex));

        return R.ok().data("TeamAttendances",new JSONArray(pageData))
                .data("TeamAttendancesSize",pageData.size());
    }

}
